package org.jamin.lending.controller.manager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jamin.lending.domain.BJUIAjaxResult;
import org.jamin.lending.domain.entity.Auser;
import org.jamin.lending.domain.entity.BorrowInfo;
import org.jamin.lending.domain.form.manger.BorrowInfoForm;
import org.jamin.lending.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "admin/borrow")
public class BorrowManagerController {

    private Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private BorrowService borrowService;

    @RequestMapping(value = "index")
    public String index(BorrowInfoForm borrowInfoForm, ModelMap modelMap) {
        Page<BorrowInfo> borrowInfos = this.borrowService.findBorrowList(borrowInfoForm);
        modelMap.addAttribute("borrowInfos", borrowInfos);
        return "manager/borrow/index";
    }

    @RequestMapping(value = "create",method = RequestMethod.GET)
    public String toCreate(BorrowInfo borrowInfo, ModelMap modelMap) {
        modelMap.addAttribute("borrowInfo",borrowInfo);
        modelMap.addAttribute("borrowTypes",BorrowInfo.Type.values());
        return "manager/borrow/create";
    }

    @ResponseBody
    @RequestMapping(value = "create",method = RequestMethod.POST)
    public BJUIAjaxResult doCreate(BorrowInfo borrowInfo,ModelMap modelMap){
        BJUIAjaxResult bjuiAjaxResult = new BJUIAjaxResult();
        try{
            Auser auser = (Auser) modelMap.get("auser");
            this.borrowService.createBorrow(borrowInfo,auser);
        }catch (Exception e){
            bjuiAjaxResult.setStatusCode(300);
            bjuiAjaxResult.setMessage("保存失败");
        }
        log.info(borrowInfo.toString());
        return bjuiAjaxResult;
    }

    @RequestMapping(value = "preliminary",method = RequestMethod.GET)
    public String toPreliminary(BorrowInfoForm borrowInfoForm,ModelMap modelMap) {
        modelMap.addAttribute(borrowInfoForm);
        Page<BorrowInfo> borrowInfos = this.borrowService.findBorrowListByStatus(borrowInfoForm,BorrowInfo.Status.PRELIMINARY);
        modelMap.addAttribute("borrowInfos",borrowInfos);
        return "manager/borrow/index";
    }

    @RequestMapping(value = "preliminary",method = RequestMethod.POST)
    public BJUIAjaxResult doPreliminary(){
        return null;
    }

    @RequestMapping(value = "release")
    public String release() {
        return "manager/borrow/index";
    }

}
